package com.itcast.service.impl;

import com.itcast.mapper.BookMapper;
import com.itcast.mapper.BorrowMapper;
import com.itcast.pojo.Borrow;
import com.itcast.service.BorrowService;
import com.itcast.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class BorrowServiceImpl implements BorrowService {
    @Autowired
    private BorrowMapper borrowMapper;
    @Autowired
    private BookMapper bookMapper;

    /**
     * 借阅图书
     * @param bookId
     * @param request
     */
    @Override
    @Transactional
    public void borrow(Integer bookId, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId =(Integer) JwtUtils.parseJWT(token).get("id");
        bookMapper.reduceStock(bookId);
        Borrow borrow = new Borrow();
        borrow.setUserId(userId);
        borrow.setBookId(bookId);
        borrow.setCreateTime(LocalDateTime.now());
        borrow.setUpdateTime(LocalDateTime.now());
        borrowMapper.insert(borrow);
    }

    /**
     * 根据用户id展示用户借阅情况
     * @param request
     * @return
     */
    @Override
    public List<Borrow> display(HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId =(Integer) JwtUtils.parseJWT(token).get("id");
        List<Borrow> list = borrowMapper.getByUserId(userId);
        return list;
    }

    /**
     * 归还图书
     * @param id
     */
    @Override
    @Transactional
    public void returnBook(Integer id) {
        Borrow borrow = borrowMapper.getById(id);
        bookMapper.addStock(borrow.getBookId());
        borrowMapper.delete(id);
    }
}
